var tempNode;
var weatherNode;
var windNode;
var latlng;
// index.html初始化函
function init() {
document.addEventListener("deviceready", loadRssChannelTemp, true);
/*$(document).ready(function(){
    loadRssChannelTemp();
});*/
}
// 页面初始化
function loadRssChannelTemp() {
//document.addEventListener("backbutton", onBackKeyDown, true);
onDeviceReady();
loadConfig();
loadRssChannel();
//initDatabase();
    // 页面加载完成，读取几个必要的节点的值作为变量，供后续代码使用
	tempNode=document.getElementById("temp");
	weatherNode=document.getElementById("weather");
	windNode=document.getElementById("wind");
}

function onDeviceReady() {
	// 设备主板就绪后，读取文件中的配置文件
	// window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
	// 设备准备就绪后，查询当前地理位置
	navigator.geolocation.getCurrentPosition(onPosSuccess, onPosError);
}

// onSuccess Geolocation
// onSuccess获取当前位置成功时的回调函数
function onPosSuccess(position) {
	
	latlng = position.coords.latitude + "," + position.coords.longitude;
	// latlng="34.284453,108.232498";
	// var latlng="42.60162,122.76123"; //辽宁省阜新市彰武县
	getCity(latlng);
}

// onPosError Callback receives a PositionError object
// onPosError获取当前位置失败时的回调函数
function onPosError(error) {
	alert("当前位置获取出现未知异常！\n请不要刻意关闭获取位置信息的服务");
	getCity(latlng)
	//alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

// 通过移动设备的经纬度获得用户所在地的市级地名
function getCity(latlng) {
	if(!latlng || latlng == null){
		latlng="32.046497,118.777313";
	}
	
	$.ajax({
           type:"get",
           url:"http://maps.googleapis.com/maps/api/geocode/json", 
           data:{
           latlng : latlng,
           sensor : "true"
           },
           success:function(data) {
           var cityname = "";
           //json = eval("(" + data + ")");
           //alert(data);
           var jsonData=data;
           //alert(jsonData.status);
           if(jsonData.status=="OK"){
           for ( var i in jsonData.results[0].address_components) {
           if (jsonData.results[0].address_components[i].types[0] == "locality") {
           cityname = jsonData.results[0].address_components[i].long_name;
           break;
           }
           }
           }else{
           cityname="南京";
           }
           
           if(cityname.length>5){
           $("#cityname").css("font-size","24px");
           }else if(cityname.length>2){
           $("#cityname").css("font-size","29px");
           }
           
           
           var cityNode=document.getElementById("cityname");
           
           cityNode.innerHTML=cityname;
           getWeatherInfo(cityname);
           },
           error:function(){
           alert("error!");
           var cityname="南京";
           var cityNode=document.getElementById("cityname");
           cityNode.innerHTML=cityname;
           getWeatherInfo(cityname);
           }
           }, "text");
    
}

// 通过城市名得到未来5天的天气数据
function getWeatherInfo(cityname){
    var cityid;
    var citykey=cityname.replace(" ","_");
    try{
        cityid=eval("obj."+citykey);
    //alert(cityid);
    }catch(error){
        if(!cityid){
            cityid="101190101";
        }
    }
    if(!cityid){
        
        cityid="101190101";
    }
	var url="http://m.weather.com.cn/data/"+cityid+".html";
	// alert(url);
	$.get(url,function(data){
          alterNowWeatherData(data);
          },"text"); 
}
// 根据最新数据，修改程序中，关于天气信息的数据
function alterNowWeatherData(data){
	var data=eval("("+data+")");
	tempNode.innerHTML=data.weatherinfo.temp1;
	weatherNode.innerHTML=data.weatherinfo.weather1;
	windNode.innerHTML=data.weatherinfo.wind1;
	
	var imageUrl="../css/images/weather/"+eval("imagesObj."+data.weatherinfo.img_title1);
	
	$("#weather_image").css("background","url("+imageUrl+") no-repeat");
}

// 读取系统配置文件
// 更换主题index.html
function loadConfig() {

var theme;
if(localStorage.theme){
    //var index = localStorage.theme.charCodeAt() -97;
    theme = localStorage.theme;
}else{
    theme = "c";
    localStorage.theme = theme;
}
if(!localStorage.autoFlush){
    localStorage.setItem("autoFlush","1");
}
changeTheme(theme);
}
// 读取rss配置文件
function loadRssChannel() {
// 执行java插件成功后的函数

var success = function(data) {
    var jsonObj = eval(data);
    //alert(jsonObj.toString());
    var length = jsonObj.length;
    
    var show = "";
    var reflushString = "刷新频道";
    //alert(jsonObj[0].url);
    for ( var i = 0; i < length; i++) {
        if (jsonObj[i].enable) {
            var temp = jsonObj[i].url.replace(/http\:\/\//, "").replace(/\./g,
                    "___").replace(/\//g, "---");
            show += "<div data-role='collapsible' id='";
            show += temp;
            show += "'><h4>";
            var icon = geticoExt(jsonObj[i].url);
            show += "<img src='" + icon + "'/>";

            show += jsonObj[i].name;
            show += "</h4><ul data-role='listview' data-inset='false' data-divider-theme='b' id='";
            show += temp;
            show += "'><li class='list-item-schedule' data-theme='c' data-icon='refresh'><a href='#' onclick='loadRss(&#39;";
            show += jsonObj[i].url;
            show += "&#39;);'><div align='center'>" + reflushString
                    + "</div></a></li></ul></div>";
           //var items = loadFromDatabase(jsonObj[i].url);
           //queryRSSCatch('SELECT * FROM RSSCATCH WHERE url = '+'"'+url+'"',jsonObj[i].url);                    
        }
                                   
    }
    finishProcess("启动完成");
    $("#channelList").html(show);
    $("#channelList").trigger('create');
    for(var i = 0;i<length;i++){
        if(jsonObj[i].enable){
           /* var db = window.openDatabase("gaprss", "1.0", "gaprssDatabase", 200000);
            db.transaction(queryRSSCatch,function(){alert("error")});
            queryRSSCatch('SELECT * FROM RSSCATCH',loadRssCatch,jsonObj[i].url);                          
        */
                                   var temp = jsonObj[i].url.replace(/http\:\/\//, "").replace(/\./g,
                                                                     "___").replace(/\//g, "---");                                     
            var key = "catch_"+temp;
            var rsscatch = localStorage[key];
              //alert(rsscatch);
             if(rsscatch){                 
             var rss = eval(rsscatch);
             //alert(rss[i].title);
            loadRssCatch(jsonObj[i].url,rss);
            }
        }
    }
    

};
var error = function(e) {
    errorProcess("启动失败,请检查配置");
};

//window.plugins.loadChannnelAndroid01API.loadChannel(success, error, null);
loadChannel(success);
}

/*function queryRSSCatch(tx){
    alert(2);
     tx.executeSql('SELECT * FROM RSSCATCH',[],rssCatchSuccess,function(e){alert("error:"+e.code));
}
function rssCatchSuccess(tx,results){
    alert(results.rows.itmes[0].title);
    loadRssCatch(targetUrl,results.rows);
}*/
// 读取rss缓存
function loadRssCatch(url,data) {
    var length = data.length;
    //alert(length);
    var show = '';
    // alert(data[1].title);
    for ( var i = 0; i < length; i++) {
        var temp = data[i].description.replace(/<\/a>/, "").replace(
                /<a.*html'>/, "");
        temp = depDecode(temp);
        show += '<li class="list-item-schedule" data-theme="c"><a href="#" onclick=go(&#39;';
        show += data[i].link;
        //show+="info.html";
        show += '&#39;)><div class="list-item-content-schedule"><h4>';
        show += data[i].title;
        show += '</h4><p class="session-time-speaker">';
        show += data[i].updated;
        show += '</p><p>';
        show += temp;
        show += '</p></div></a></li>';
    }
    // alert(11);
    // alert(show);
    url = url.replace(/http\:\/\//, "").replace(/\./g, "___").replace(
            /\//g, "---");
    // alert(url);
    $("ul#" + url).append(show);
    $("ul#" + url).listview('refresh');

}
// 读取rss具体信息
function loadRss(url) {
// 状态栏显示正在加载
//	showProcess("正在加载...");
$.mobile.showPageLoadingMsg("a","正在刷新请稍后",true);
// 执行java插件成功后的函数
var success = function(data) {
    // 状态栏显示完成加载
//		finishProcess("加载完成");
    $.mobile.hidePageLoadingMsg ();
    var length = data.items.length;

    var show = "<li class='list-item-schedule' data-theme='c' data-icon'refresh'><a href='#' onclick='loadRss(&#39;";
    show += url;
    show += "&#39;);'><div align='center'>刷新频道</div></a></li>";
    ;
    for ( var i = 0; i < length; i++) {
        var temp = data.items[i].description.replace(/<\/a>/, "").replace(
                /<a.*html'>/, "");
        //temp = depDecode(temp);
        show += '<li class="list-item-schedule" data-theme="c"><a href="#" onclick=go(&#39;';
        show += data.items[i].link;
        show += '&#39;)><div class="list-item-content-schedule"><h4>';
        show += data.items[i].title;
        show += '</h4><p class="session-time-speaker">';
        show += data.items[i].updated; 
        show += '</p><p>';
        show += temp;
        show += '</p></div></a></li>';
    }
    // alert(11);
    // alert(show);
    url = url.replace(/http\:\/\//, "").replace(/\./g, "___").replace(
            /\//g, "---");
    
    $("ul#" + url).html(show);
    $("ul#" + url).listview('refresh');
    saveToDataBase(url,data);
};

var error = function(e) {
//		errorProcess("加载失败,请检查网络");
    $.mobile.hidePageLoadingMsg ();
    alert("加载失败,请检查网络"+url);

};

loadRssImpl(success, url);
}
function depEncode(code){
   var c = code.replace(/\'/g,"%5");  
   // c= c.replace(/\//g,"%6");
     //            c=c.replace(/\:/g,"%7");
  //c="[sdf]";
    c = c.replace(/\n/g,"");
     return  c;
}
function depDecode(code){
    
   var c = code.replace(/%5/g,"'"); 
    return c;
}
//save to database
function saveToDataBase(url,data){
    var length = data.items.length;
    var catch1 ="[{";
    for ( var i = 0; i < length; i++) {  
        var title = data.items[i].title;
        var link = data.items[i].link; 
        var description = data.items[i].description.replace(/<\/a>/, "").replace(
            /<a.*html'>/, "");
        description =depEncode(description);
        var updated = data.items[i].updated;
       /* executeSql('INSERT INTO RSSCATCH (url,title,link,description,updated) VALUES ("'+url+'","'+title+'","'+link+'","'+description+'","'+updated+'")');*/
        catch1 += "title:'"+title+"',link:'"+link+"',description:'"+description+"',updated:'"+updated+"'}";
        if(i!=length-1){
           catch1+=",{";              
        }else{
           catch1+="]";              
        }
        
    }
   // alert(catch1); 
    //var json = eval(catch1);
   // alert(json.length);  
    localStorage.setItem("catch_"+url,catch1);
    var key = "catch_"+url;
                  
    //alert(localStorage[key]);
  //  alert(key+" "+json[0].title);
}


//获取rss源具体信息
function loadRssImpl(callback,url){
jQuery.getFeed({
                url: url,
                success:function(feed){ 
                    callback(feed);
                }
               }
); 
}
//读取配置文件中的频道
function loadChannel(success){
if(localStorage.channel){
    //alert(localStorage.channel);
    /* var data =  "[{id:'rss_newstop',name:'网易头条新闻',url:'http://news.163.com/special/00011K6L/rss_newstop.xml',enable:true},{id:'rss_gn',name:'网易国内新闻',url:'http://news.163.com/special/00011K6L/rss_gn.xml',enable:true},{id:'rss_gj',name:'网易国际新闻',url:'http://news.163.com/special/00011K6L/rss_gj.xml',enable:true},{id:'sohu.pic',name:'搜狐图片新闻',url:'http://news.sohu.com/rss/pfocus.xml',enable:true},]";
     var json = eval(data);
     //alert(json.length);
     localStorage.setItem('channel', data);*/
     success(localStorage.channel);
}else{
     var data = "[{id:'rss_newstop',name:'网易头条新闻',url:'http://news.163.com/special/00011K6L/rss_newstop.xml',enable:true},{id:'rss_gn',name:'网易国内新闻',url:'http://news.163.com/special/00011K6L/rss_gn.xml',enable:true},{id:'rss_gj',name:'网易国际新闻',url:'http://news.163.com/special/00011K6L/rss_gj.xml',enable:true},{id:'sohu.pic',name:'搜狐图片新闻',url:'http://news.sohu.com/rss/pfocus.xml',enable:false}]";
     //var json = eval(data);
     //alert(json.length);
     localStorage.setItem('channel', data);
    success(localStorage.channel);
}
}
// 显示加载动画
function showProcess(msg) {
if (msg == null) {
    msg = "loading";
}

$("#message").html(msg);
$("#message").trigger('create');
$("#messagePic").attr("src", "../css/images/loading.gif");
$("#messagePic").animate({
    src : "../css/images/loading1001.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading1003.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading1005.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading1007.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading1009.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading10011.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading10013.jpg"
}, "slow");
$("#messagePic").animate({
    src : "../css/images/loading10015.jpg"
}, "slow");
$("#messageFrame").fadeIn(2000);

}
function go(url) {
	var baiduzm = "http://gate.baidu.com/tc?bd_page_type=4&src=";
	var src = url.replace(/http\:\/\//, "").replace(/\//g, "%2F");
	// 设备的网络
	var networkState = navigator.network.connection.type;

	
		// 将新闻地址存储到本地html
		localStorage.url = baiduzm + src;
		localStorage.src = url;
		localStorage.filename = src;
		$.mobile.showPageLoadingMsg("c", "Loading...", true);
		window.location.href = "info.html";
	
}
// 完成加载动画
function finishProcess(msg) {
if (msg == null) {
    msg = "finish";
}
$("#messagePic").attr("src", "../css/images/finish.png");
$("#message").html(msg);
$("#messageFrame").fadeOut(2000);
}
// 获取网站的ico图标
function geticoExt(url) {
var icoUrl;
if (url.indexOf(".com/") != -1) {
    icoUrl = url.substring(0, url.indexOf(".com/") + 5);
} else if (url.indexOf(".cn/") != -1) {
    icoUrl = url.substring(0, url.indexOf(".cn/") + 4);
} else if (url.indexOf(".net/") != -1) {
    icoUrl = url.substring(0, url.indexOf(".net/") + 5);
} else if (url.indexOf(".org/") != -1) {
    icoUrl = url.substring(0, url.indexOf(".org/") + 5);
}
icoUrl += "favicon.ico";
return icoUrl;
}